package com.cz.nongyetongv5.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.NewsListAdapter;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.bean.New;
import com.cz.nongyetongv5.bean.NewsTitle;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.CustomListView;
import com.cz.nongyetongv5.custom.CustomListView.OnLoadListener;
import com.cz.nongyetongv5.custom.CustomListView.OnRefreshListener;
import com.cz.nongyetongv5.dialog.LoadingDialog;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.DialogUtil;
import com.cz.nongyetongv5.utils.HttpUtils;
import com.cz.nongyetongv5.utils.HttpUtils.OnRequestExecuted;

public class NewListItemFragment extends Fragment {

	/**
	 * 用来控制进度条是否显示
	 */
	private NewsListActivity newsListActivity = null;

	private NewsTitle title = null;

	/**
	 * 新闻的下拉列表
	 */
	private CustomListView clvNewsList = null;

	/**
	 * 用户对象
	 */
	private User user = null;

	/**
	 * 刷新任务
	 */
	private AsyncTask<Integer, Integer, Integer> atRefresh = null;

	/**
	 * 每页的大小
	 */
	private int limit = 20;

	/**
	 * 当前页
	 */
	private int currentPage = 0;

	// 从第几个数据开始的
	private int offset = currentPage * limit;

	// 总页数
	private int totalPage = 0;

	/**
	 * 所有的新闻对象
	 */
	private List<New> news = new ArrayList<New>();

	/**
	 * 适配器
	 */
	private NewsListAdapter nlaAdapter = null;

	public static final int FORWORD_DETAIL_REQUEST_CODE = 1001;

	/**
	 * 检测是否是只显示只读的列表
	 */
	private boolean unreadlist = false;

	private LoadingDialog dia;

	public static NewListItemFragment getNewInstance(NewsTitle title,
													 NewsListActivity newsListActivity) {

		NewListItemFragment fragment = new NewListItemFragment();

		fragment.title = title;

		fragment.newsListActivity = newsListActivity;

		return fragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {

		/**
		 * 清除消息
		 */
		NotificationManager notificationManager = (NotificationManager) getActivity()
				.getSystemService(Context.NOTIFICATION_SERVICE);

		notificationManager.cancel(0);

		if (getActivity() != null && getActivity().getIntent() != null) {
			if (getActivity().getIntent().getSerializableExtra("user") != null) {
				user = (User) getActivity().getIntent().getSerializableExtra(
						"user");

			}

		}

		clvNewsList = (CustomListView) inflater.inflate(
				R.layout.newslist_pager, null);

		clvNewsList.setonRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {

				// 初始化页数,从第一个开始加载
				currentPage = 0;

				refresh(0);
			}
		});

		/**
		 * 加载更多
		 */
		clvNewsList.setonLoadListener(new OnLoadListener() {

			@Override
			public void onLoad() {

				loadNextPage();

			}
		});

		nlaAdapter = new NewsListAdapter(getActivity(), news);

		clvNewsList.setAdapter(nlaAdapter);

		clvNewsList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
									int postion, long arg3) {

				New newObj = (New) arg0.getItemAtPosition(postion);

				Intent to_new_detail = new Intent(getActivity(),
						NewDetailActivity.class);

				to_new_detail.putExtra("id", newObj.getId());

				to_new_detail.putExtra("new", newObj);
				to_new_detail.putExtra("title", title.getName());
				to_new_detail.putExtra("user", user);
				to_new_detail.putExtra("position", postion);

				startActivityForResult(to_new_detail,
						FORWORD_DETAIL_REQUEST_CODE);

			}
		});

		// 如果是第一个则加载
		int postion = getActivity().getSupportFragmentManager().getFragments()
				.indexOf(this);

		if (postion == 0) {
			this.refreshListView(false);
		}

		return clvNewsList;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == FORWORD_DETAIL_REQUEST_CODE) {

			int position = data.getExtras().getInt("position");

			position--;

			if (unreadlist) {

				news.remove(position);

				nlaAdapter.notifyDataSetChanged();

			} else {

				news.get(position).setRead(true);

				nlaAdapter.notifyDataSetChanged();
			}

		}

		super.onActivityResult(requestCode, resultCode, data);

	}

	public int loadNextPage() {

		if (totalPage <= currentPage) {

			// 设置进度条不显示
			newsListActivity.toggleProgress(false);

			clvNewsList.onLoadComplete();

			return -1;
		} else {
			currentPage = currentPage + 1;

			refresh(1);

			// try {
			// Thread.sleep(300);
			// } catch (InterruptedException e) {
			// e.printStackTrace();
			// }

			return 1;
		}
	}

	/**
	 * 刷新列表
	 */
	public void refresh(int type) {

		if (atRefresh == null || atRefresh.getStatus() == Status.FINISHED) {
			dia = new LoadingDialog(getActivity());
			dia.setCanceledOnTouchOutside(false);
			dia.show();
			loadNews(type);

		}

	}

	public void loadNews(final int type) {

		atRefresh = new AsyncTask<Integer, Integer, Integer>() {

			private int responseCodeRet;

			private String responseBodyRet;

			@Override
			protected void onPreExecute() {

				// 设置进度条显示
				newsListActivity.toggleProgress(true);
				// 如果是刷新局部数据并且总页数小于等于当前页
				if (type == 1 && totalPage <= currentPage) {

					Toast.makeText(getActivity(), "已经无更多数据..",
							Toast.LENGTH_SHORT).show();

					// 设置进度条不显示
					newsListActivity.toggleProgress(false);

					clvNewsList.onLoadComplete();

					cancel(true);
				}

			}

			@Override
			protected Integer doInBackground(Integer... params) {

				HttpUtils httpUtils = HttpUtils.getInstance();

				httpUtils.setOnRequestExecuted(new OnRequestExecuted() {

					@Override
					public void onRequestExecuted(int responseCode,
												  String responseBody) {

						responseCodeRet = responseCode;

						responseBodyRet = responseBody;
					}
				});

				// 计算officeset
				offset = currentPage * limit;

				String authUserName = new ConfigUtil(getResources())
						.getRestUsername();

				String authPassword = new ConfigUtil(getResources())
						.getRestPassword();

				String requestUrl = getString(R.string.download_news_list);

				requestUrl = new ConfigUtil(getResources()).getPreHttpUrl()
						+ requestUrl + "region_code/" + user.getCityId()
						+ "/offset/" + offset + "/limit/" + limit
						+ "/category/" + title.getId();

				if (unreadlist) {

					requestUrl = getString(R.string.download_news_list_unread);

					requestUrl = new ConfigUtil(getResources()).getPreHttpUrl()
							+ requestUrl + "region_code/" + user.getCityId()
							+ "/offset/" + offset + "/limit/" + limit
							+ "/category/" + title.getId();
				}

				if (user != null && CharsetUtil.isNotNull(user.getUsername())) {

					requestUrl += "/username/" + user.getUsername();

				}

				httpUtils.sendRequest(requestUrl, null, "GET", "UTF-8",
						authUserName, authPassword, user);

				return params[0];
			}

			@Override
			protected void onPostExecute(Integer result) {

				// 设置进度条不显示
				newsListActivity.toggleProgress(false);

				switch (responseCodeRet) {
					case HttpUtils.SUCCESS:

						try {
							dia.dismiss();
							JSONObject jsonObject = new JSONObject(responseBodyRet);

							int total = jsonObject.getInt("total");

							totalPage = total % limit == 0 ? total / limit
									: (total / limit) + 1;

							JSONArray jsonArray = jsonObject.getJSONArray("result");

							/**
							 * 0 说明是刷新全部数据 1. 说明是分页刷新
							 */
							if (result == 0) {
								// 清除数据
								news.clear();
							}

							for (int i = 0; i < jsonArray.length(); i++) {

								JSONObject newsJson = jsonArray.getJSONObject(i);

								String id = newsJson.getString("id");

								String title = newsJson.getString("title");

								String content = newsJson.getString("intro");

								String date = newsJson.getString("date");

								String imageUrl = null;

								if (!newsJson.isNull("image")) {
									imageUrl = newsJson.getString("image");

									if (!imageUrl.startsWith("http://")) {
										imageUrl = new ConfigUtil(getResources())
												.getPreHttpUrl() + ".." + imageUrl;
									}

								}

								boolean isRead = true;

								if (!newsJson.isNull("is_read")) {

									int is_read = newsJson.getInt("is_read");

									if (is_read < 1) {

										isRead = false;
									}

								}

								New newObj = new New(id, title, content, date,
										NewListItemFragment.this.title.getName(),
										imageUrl, isRead);

								news.add(newObj);

							}

							nlaAdapter.notifyDataSetChanged();
							if (result == 0) {
								clvNewsList.onRefreshComplete();
							} else {
								clvNewsList.onLoadComplete();
							}

						} catch (JSONException e) {

							DialogUtil.showMessageDialog(
									getActivity().getString(
											R.string.message_softerror), null,
									getActivity());
						}

						break;

					case HttpUtils.TIMEOUT:
						DialogUtil.showMessageDialog(
								getActivity().getString(
										R.string.message_socktimeout), null,
								getActivity());
						dia.dismiss();
						break;

					case HttpUtils.NETWORK_ERR:
						dia.dismiss();
						DialogUtil.showMessageDialog(
								getActivity().getString(R.string.error_no_network),
								null, getActivity());
						break;

					case HttpUtils.UNKNOWERROR:
						dia.dismiss();
						DialogUtil
								.showMessageDialog(
										getActivity().getString(
												R.string.message_softerror), null,
										getActivity());
						break;
				}
			}

		};

		atRefresh.execute(type);

	}

	/**
	 * 模拟ListView下拉进行刷新
	 *
	 * @param must
	 *            : 是否必须刷新
	 */
	public void refreshListView(boolean must) {

		if (must) {

			clvNewsList.onTouchEvent(MotionEvent.obtain(
					SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
					MotionEvent.ACTION_DOWN, 500, 400, 0));

			clvNewsList.onTouchEvent(MotionEvent.obtain(
					SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
					MotionEvent.ACTION_MOVE, 531, 500, 0));
			clvNewsList.onTouchEvent(MotionEvent.obtain(
					SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
					MotionEvent.ACTION_MOVE, 531, 600, 0));
			clvNewsList.onTouchEvent(MotionEvent.obtain(
					SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
					MotionEvent.ACTION_MOVE, 531, 700, 0));
			clvNewsList.onTouchEvent(MotionEvent.obtain(
					SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
					MotionEvent.ACTION_MOVE, 531, 800, 0));

			clvNewsList.onTouchEvent(MotionEvent.obtain(
					SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
					MotionEvent.ACTION_MOVE, 531, 920, 0));
			clvNewsList.onTouchEvent(MotionEvent.obtain(
					SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
					MotionEvent.ACTION_UP, 531, 920, 0));

		} else {

			if (this.news.size() < 1) {

				clvNewsList.onTouchEvent(MotionEvent.obtain(
						SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
						MotionEvent.ACTION_DOWN, 500, 400, 0));

				clvNewsList.onTouchEvent(MotionEvent.obtain(
						SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
						MotionEvent.ACTION_MOVE, 531, 500, 0));
				clvNewsList.onTouchEvent(MotionEvent.obtain(
						SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
						MotionEvent.ACTION_MOVE, 531, 600, 0));
				clvNewsList.onTouchEvent(MotionEvent.obtain(
						SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
						MotionEvent.ACTION_MOVE, 531, 700, 0));
				clvNewsList.onTouchEvent(MotionEvent.obtain(
						SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
						MotionEvent.ACTION_MOVE, 531, 800, 0));

				clvNewsList.onTouchEvent(MotionEvent.obtain(
						SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
						MotionEvent.ACTION_MOVE, 531, 920, 0));
				clvNewsList.onTouchEvent(MotionEvent.obtain(
						SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
						MotionEvent.ACTION_UP, 531, 920, 0));

			}

		}

	}

	/**
	 * 增加一个新闻
	 */
	public void addNew(New newObj) {

		if (news.size() > 1) {

			news.add(0, newObj);

			nlaAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * 清理列表缓存资源
	 */
	@Override
	public void onDestroy() {

		if (this.nlaAdapter != null
				&& this.nlaAdapter.getmImageLoader() != null) {
			this.nlaAdapter.getmImageLoader().clearCache();
		}

		super.onDestroy();
	}

	/**
	 * 根据已经获得的未读位置查找下一个未读位置
	 *
	 * @param position
	 * @return
	 */
	public int getNewNextPosition(int position) {

		int searchPosition = nlaAdapter.getNewIndex(position);

		if (searchPosition != -1) {
			clvNewsList.setSelection(searchPosition);
		} else if (position != -1) {
			clvNewsList.setSelection(position);

		}

		return searchPosition;

	}

	public void setUnreadlist(boolean unreadlist) {

		/**
		 * 每页的大小
		 */
		this.limit = 20;

		/**
		 * 当前页
		 */
		this.currentPage = 0;

		// 从第几个数据开始的
		this.offset = currentPage * limit;

		// 总页数
		this.totalPage = 0;

		this.unreadlist = unreadlist;
	}

	public boolean getUnreadlist() {
		return this.unreadlist;
	}

}
